/*

Input: newdata/estimation_prep_ltw18 [prepared precinct-level panel]

Output: Figure C.6, C.7

Task: RR (2023), honest DiD, robustness to violation of PT assumption

*/	
	
* PULL: Precinct-level panel
	use "$newdata/estimation_prep_ltw18.dta", clear

********************************************************************************
	//	 Prep Estimation //
********************************************************************************
	
	// compute id for DISTANCE increase/decrease, 0 else
	gen 	tmp = (del_street_dist>0) 			if K==0
	bys sb_new (tmp): gen ind_dist_up = tmp[1]
	replace ind_dist_up = 0 					if missing(Ei)
	lab var ind_dist_up "=1 if dist increase in event, 0 else"
	
	cap drop tmp*
	gen 	tmp = (del_street_dist<0) 			if K==0
	bys sb_new (tmp): gen ind_dist_dn = tmp[1]
	replace ind_dist_dn = 0 					if missing(Ei)
	lab var ind_dist_dn "=1 if dist decrease in event, 0 else"		
		
	// set global for outcomes (saved in global b/c order must not change below)
	global outcomes turnout_urne turnout_pos_req turnout_tot_req
		
	
********************************************************************************
		// RR (2023), honest DID: Baseline Estimates //
********************************************************************************
	
 * 1) Estimate baseline Event Study 
 
	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	order F1event, last
	
	// Estimate baseline ES
	estimates clear 
 
 foreach v of varlist $outcomes {
	
		reghdfe `v' F7event-L7event F1event $ctr $wgt if smpl_trim==1, absorb(i.wahl_id#i.stadtbez i.sb_new) cluster(sb_new)
		
	estimates store `v'
 }

 * 2) Extract estimates: STORES coefs + 95% CI in new vars: __event_H, __event_coef, __event_hi, __event_lo (with index= 1,2, and 3)
	event_plot  $outcomes, ///
	stub_lag(L#event) stub_lead(F#event) trimlead(4) trimlag(2)  savecoef noplot
	 
	 
 * 3) Compute Roth & Ramabach (ReStud, 2023) CI for post-treatment coefs
 cap drop __M*
 local c=1							// counter for outcome variables, 1=inperson, 2=mail-in, 3=total
 foreach v of varlist $outcomes {
	 // LOAD estimates
	 qui estimates restore `v'
	 
	 // store "honest" CI here
	 gen __M_lb`c' =. 
	 gen __M_ub`c' =.
	 
	 // set M; M=0 with delta=sd means allowing for linear violations of PT 
	 local M=0
	 
	 // Loop over 3 post-treatment Coefs (in chronological order these are estimates 7,8, and 9)
	 forvalues t=0/2 {
	 	
		* HonestEventStudy 
		
		// set l_vec matrix to obtain results for coef of interest (i.e. t=0, t=1, t=2), e.g. (1 \ 0 \ 0) for t=0
		matrix l_vec = cond(`t'==0,1,0) \ cond(`t'==1,1,0) \ cond(`t'==2,1,0)
	 	honestdid, pre(4/6) post(7/9) mvec(`M') delta(sd) l_vec(l_vec)
		
		// extract "honest" CI and in variables
		mata: st_local("lb", strofreal(`s(HonestEventStudy)'.CI[2,2]))  // extract lower honest CI bound
		mata: st_local("ub", strofreal(`s(HonestEventStudy)'.CI[2,3]))  // extract upper honest CI bound
		replace __M_lb`c'=  `lb' if __event_H1== `t'
		replace __M_ub`c'=  `ub' if __event_H1== `t'
		
	}
	local ++c
 }	
	 
 * 4) Plot results with bsl. CI and "honest" CI	 
	forvalues j = 1/3 {
		if `j'==1{
			local ttl "title({bf:Panel A.} Effect on Polling Place Turnout, just(left) span bexpand size(medium))"
		}
		if `j'==2{
			local ttl "title({bf:Panel B.} Effect on Mail-in Turnout, just(left) span bexpand size(medium))"
		}
		if `j'==3 {
			local ttl "title({bf:Panel C.} Effect on Total Turnout, just(left) span bexpand size(medium))"
		}
		
		tw (connect __event_coef`j' __event_H`j' , sort lcol(black) ms(O) msize(2.5pt) mcol(black)) ///
			(rcap __event_lo`j' __event_hi`j' __event_H`j', col(black)) ///
			(rcap __M_lb`j' __M_ub`j' __event_H`j', col(red) lpat(-)) ///
			, `ttl' ytitle("Voter turnout in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			xline(-0.5, lcol(black) lpat(solid)) yline(0, lcolor(gray) lpat(solid)) name(gr`j', replace) ///
			legend(order(2 "95% CI" 3 "95% CI due to RR (2023) allowing for" "linear violations of PT assumption") pos(12))
	}			
				
	* PLOT: FIGURE C6. Rob to linear violations of PT assumption–Pooled Reassignments				
	grc1leg2  gr1 gr2 gr3 , xcommon  col(2) iscale(.8) name(bsl_honestdid, replace) ///
		pos(4) ring(0) lcol(1) imargins(small)  ///
					lxoffset(0) lyoffset(19) legscale(*.9)
	graph export "$figures/Figure_C6_ES_RR_2023_bsl.pdf",replace
	
	cap drop __*
	
* 5) breakdown value for manuscript 
	estimates restore turnout_tot_req
	matrix l_vec = 1 \ 0 \ 0
	honestdid, pre(4/6) post(7/9) mvec(0(.005).1) delta(sd) l_vec(l_vec) 

	

*********************************************************************************
	// RR (2023) sensitvity for heterogeneity by distance increase/ decrease //
*********************************************************************************	
	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	// Create two set of dummies: Reason Dummy x event-time dummies
	forvalues l = 7(-1)1 {		
		gen 	F`l'event_a = F`l'event *ind_dist_dn				// a := decrease
		lab var F`l'event_a "(N-)x\hspace{.7cm}Reassignment (#t-`l'#)"
		gen	 	F`l'event_b = F`l'event *ind_dist_up				// b:= increase
		lab var F`l'event_b "(N+)x\hspace{.7cm}Reassignment (#t-`l'#)"

		assert  F`l'event_b+F`l'event_a==F`l'event		
	}
	forvalues l = 0/7 {		
		gen 	L`l'event_a = L`l'event *ind_dist_dn	// a := decrease
		lab var L`l'event_a "(N-)x\hspace{.7cm}Reassignment (#t+`l'#)"
		gen	 	L`l'event_b = L`l'event *ind_dist_up	// b:= increase
		lab var L`l'event_b "(N+)x\hspace{.7cm}Reassignment (#t+`l'#)"
		assert  L`l'event_b+L`l'event_a==L`l'event	
	}
	// ORDER dummies
	order *event_b, last
	order F1event*,last	
	
 * 1) Estimate event studies	
	// Estimate ES by increase/decrease in distance
	estimates clear
	foreach v of varlist $outcomes {
	
		qui reghdfe `v' F7event_a-L7event_a  F7event_b-L7event_b F1event_a F1event_b ///
					$ctr $wgt if smpl_trim==1 , absorb(i.wahl_id#i.stadtbez i.sb_new) cluster(sb_new)

		estimates store `v'
	}
	
	
 * 2) Extract estimates: STORES coefs + 95% CI in new vars: __event_H, __event_coef, __event_hi, __event_lo (with index=1_a, 1_b, 2_a, etc.)
 * ADD suffix _a for DECREASE; _b for INCREASE
 
	// distance decrease
	event_plot  $outcomes, ///
	stub_lag(L#event_a) stub_lead(F#event_a) trimlead(4) trimlag(2)  savecoef noplot
	ren __* _*
	ren _* =_a
	
	// distance increase
	event_plot  $outcomes, ///
	stub_lag(L#event_b) stub_lead(F#event_b) trimlead(4) trimlag(2)  savecoef noplot
	ren __* =_b	// (reverse order here so not to rename _a_b)
	ren __* _*
	
	
 * 3) Compute Roth & Ramabach (ReStud, 2023) CI for post-treatment coefs
 cap drop _M*
 local c=1							// counter for outcome variables, 1=inperson, 2=mail-in, 3=total
 foreach v of varlist $outcomes {
	 // LOAD estimates
	 qui estimates restore `v'
	 
	 // store "honest" CI here
	 gen _M_lb`c'_a =. 
	 gen _M_ub`c'_a =.
	 gen _M_lb`c'_b =. 
	 gen _M_ub`c'_b =. 
	 
	 // set M; M=0 with delta=sd means allowing for linear violations of PT 
	 local M=0
	 
	 // Loop over 3 post-treatment Coefs (in chronological order these are estimates 7,8, and 9)
	 forvalues t=0/2 {
	 	
		* HonestEventStudy 
		
		// set l_vec matrix to obtain results for coef of interest (i.e. t=0, t=1, t=2), e.g. (1 \ 0 \ 0) for t=0
		matrix l_vec = cond(`t'==0,1,0) \ cond(`t'==1,1,0) \ cond(`t'==2,1,0)
		
		* Decrease: coefs 4--6 (preperiods), coefs 7--9 (postperiods)
			honestdid, pre(4/6) post(7/9) mvec(`M') delta(sd) l_vec(l_vec)	

			// extract results and store in variables
			mata: st_local("lb", strofreal(`s(HonestEventStudy)'.CI[2,2]))  // extract lower honest CI bound
			mata: st_local("ub", strofreal(`s(HonestEventStudy)'.CI[2,3]))  // extract upper honest CI bound
			replace _M_lb`c'_a=  `lb' if _event_H1_a== `t'
			replace _M_ub`c'_a=  `ub' if _event_H1_a== `t'
		
		* Increase: coefs 18--20 (preperiods), coefs 21--23 (postperiods)
			honestdid, pre(18/20) post(21/23) mvec(`M') delta(sd) l_vec(l_vec)	
			
			// extract results and store in variables
			mata: st_local("lb", strofreal(`s(HonestEventStudy)'.CI[2,2]))  // extract lower honest CI bound
			mata: st_local("ub", strofreal(`s(HonestEventStudy)'.CI[2,3]))  // extract upper honest CI bound		
			replace _M_lb`c'_b=  `lb' if _event_H1_a== `t'
			replace _M_ub`c'_b=  `ub' if _event_H1_a== `t'
		
	}
	
	local ++c
 }		
	

 * 4) Plot results with bsl. CI and "honest" CI	 	
	forvalues c = 1/3 {
		
		tw (connect _event_coef`c'_a _event_H`c'_a , sort lcol(black) ms(O) msize(2.5pt) mcol(black)) ///
			(rcap _event_lo`c'_a _event_hi`c'_a _event_H`c'_a, col(black)) ///
			(rcap _M_lb`c'_a _M_ub`c'_a _event_H`c'_a, col(red) lpat(-)) ///
			, xtitle("") ytitle("Voter turnout in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			xline(-0.5, lcol(black) lpat(solid)) yline(0, lcolor(gray) lpat(solid)) name(gr`c'_a, replace) ///
			subtitle("{bf:b.} Distance decrease",nobox justification(left) size(medsmall)) ///
			legend(order(2 "95% CI" 3 "95% CI due to RR (2023) allowing for" "linear violations of PT assumption") pos(12) row(1))
			
		
		tw (connect _event_coef`c'_b _event_H`c'_b , sort lcol(black) ms(O) msize(2.5pt) mcol(black)) ///
			(rcap _event_lo`c'_b _event_hi`c'_b _event_H`c'_b, col(black)) ///
			(rcap _M_lb`c'_b _M_ub`c'_b _event_H`c'_b, col(red) lpat(-)) ///
			, xtitle("") ytitle("Voter turnout in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			xline(-0.5, lcol(black) lpat(solid)) yline(0, lcolor(gray) lpat(solid)) name(gr`c'_b, replace) ///
			subtitle("{bf:a.} Distance increase",nobox justification(left) size(medsmall)) ///
			legend(order(2 "95% CI" 3 "95% CI due to RR (2023) allowing for" "linear violations of PT assumption") pos(12) row(1))
	}	
			
	
	* PLOT: FIGURE C7. Robustness to linear violations of PT assumption– Effects by Distance Change
	grc1leg2 gr1_b gr1_a, 		 name(g1, replace) ///
			title("{bf:Panel A.} Effect on Polling Place Turnout", just(left) bexpand size(small)) loff  iscale(.7) imargins(small)
	grc1leg2 gr2_b gr2_a, name(g2, replace) ///
			title("{bf:Panel B.} Effect on Mail-in Turnout", just(left) bexpand size(small)) loff  iscale(.7) imargins(small)
	grc1leg2 gr3_b gr3_a, name(g3, replace) ///
			title("{bf:Panel C.} Effect on Total Turnout", just(left) bexpand size(small))   iscale(.7) imargins(small)
	grc1leg2 g1 g2 g3, col(1) imargins(zero) legscale(*.65) lrow(1)
	gr_edit .style.editstyle declared_ysize(6) editcopy									
	graph export "$figures/Figure_C7_ES_RR_2023_dist2.pdf",replace	
	
			
				